// index.js


var app = getApp();
//HTTP请求request封装
var HttpRequest = require("../../http.js");
//CBC加密 
var CryptoJS = require("../../Crypto.js");
//RSA加密
var RSA = require("../../rsa.js"); 
// 区划加载
var tcity = require("area.js");
Page({
  data: {
    //省级区划
    provinces: [],
    province: "",//区划名称
    provinceIds:[],
    provinceId:'', //区划ID
    //市级区划
    citys: [],
    city: "",//区划名称
    cityIds: [],
    cityId: '',//区划ID
    //县级区划
    countys: [],
    county: '',//区划名称
    countyIds: [],
    countyId: '',//区划ID
    //区县级区划编码
    codes: [], 
    code: '',
    //下标选择
    value: [0, 0, 0],
    values: [0, 0, 0],
    //街道级区划
    area:'',  //街道区划名称
    areacode:'',//街道区划code
    areaId: '',//街道区划ID
    //街道选择初始下标
    index: 0,

    condition: false,//确定或者取消
    title_phone:'',//电话号码
    userName:'',//姓名  
    regex_cordid: '',//身份证校验开关(校验通过为1，未通过为2) 
    loadingHidden: true,//加载动画

  },
  getReq: HttpRequest.getReq,//GET数据请求函数
  postReq: HttpRequest.postReq,//POST数据请求
  header: HttpRequest.header,//header参数
  //身份证号码获取验证
  CordId:function(e){
   var cord_id= e.detail.value;
   console.log(cord_id);
   var regex = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/;
   if (!regex.test(cord_id)) {
     wx.showToast({
       title: '身份证号格式错误！',
       icon: 'none',
       duration: 2000
     });
     this.setData({
       regex_cordid: 2,
     })
     return false;
   }else{
     this.setData({
       regex_cordid:1,
     })
   }
  },
  //滑动事件
  bindChange: function (e) {   
    var that = this; 
    var val = e.detail.value
    console.log(val)
    var t = this.data.values; 
    console.log(t)
    var cityData = this.data.cityData;  
    //省级选择
    console.log(val[1])
    console.log(t[1])
    if (val[0] != t[0]) {
      //省级区划名字 
      const citys = [];
      const countys = [];
      //区划编码
      const codes = [];
      //区划ID
      const cityIds = []; 
      const countyIds = [];

      for (let i = 0; i < cityData[val[0]].children.length; i++) {
        citys.push(cityData[val[0]].children[i].divisionName);
        cityIds.push(cityData[val[0]].children[i].divisionId);
        codes.push(cityData[val[0]].children[i].divisionCode);
      }
      for (let i = 0; i < cityData[val[0]].children[0].children.length; i++) {
        countys.push(cityData[val[0]].children[0].children[i].divisionName);
        countyIds.push(cityData[val[0]].children[0].children[i].divisionId);
        codes.push(cityData[val[0]].children[0].children[i].divisionCode)
      }
      this.setData({
        province: this.data.provinces[val[0]],
        provinceId: this.data.provinceIds[val[0]],

        city: cityData[val[0]].children[0].divisionName,
        citys: citys,

        county: cityData[val[0]].children[0].children[0].divisionName,
        countys: countys,

        code: cityData[val[0]].children[0].children[0].divisionCode,
        codes:codes,

        cityId: cityData[val[0]].children[0].children[0].divisionId,
        cityIds: cityIds,
        
        countyId: cityData[val[0]].children[0].children[0].divisionId,
        countyIds: countyIds,

        values: val,
        value: [val[0], 0, 0]
      }) 
      return;
    }
    //市级选择
    if (val[1] != t[1]) { 
      const countys = [];
      const codes = [];
      const counIds = [];
      
      for (let i = 0; i < cityData[val[0]].children[val[1]].children.length; i++) {
        countys.push(cityData[val[0]].children[val[1]].children[i].divisionName)
        codes.push(cityData[val[0]].children[val[1]].children[i].divisionCode)
      }
      this.setData({
        city: this.data.citys[val[1]],
        cityId: this.data.cityIds[val[1]],

        county: cityData[val[0]].children[val[1]].children[0].divisionName,
        countys: countys,

        countyId: cityData[val[0]].children[val[1]].children[0].divisionId,
        counIds: counIds,

        code: cityData[val[0]].children[val[1]].children[0].divisionCode,
        codes: codes,

        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    //区县级选择
    if (val[2] != t[2]) {
      console.log(this.data.codes[val[2]]);
      var data_code = this.data.codes[val[2]];
      this.setData({
        county: this.data.countys[val[2]],
        code: this.data.codes[val[2]],
        countyId: this.data.countyIds[val[2]],
        values: val, 
      });
      //登录信息
      const login_Info = JSON.parse(wx.getStorageSync('login_Information')); //登录基础信息
      const headArray = wx.getStorageSync('UserLogin');
      const headers = {
        'Accept': 'application/json',
        "Content-Type": "application/x-www-form-urlencoded",
        "headMode": headArray,
        "token": login_Info.token,
      };

      const url = '/allreq/administrative/divisioncode/' + data_code + '';
      HttpRequest.getReq(url, data_code, headers, function (res, code) {
        const datas = res;
        const areas = [];
        const areacodes = [];
        const areaIds = [];
        for (let i = 0; i < datas.length; i++) {
          areas.push(datas[i].divisionName);
          areacodes.push(datas[i].divisionCode);
          areaIds.push(datas[i].divisionId)
        }
        that.setData({
          area: areas,
          areacode: areacodes,
          areaId: areaIds,
        })
      });
  
      return;
    }
  }, 
  //选择下级区划
  bindPickerChange:function(e){
    this.setData({
      index: e.detail.value,
    })
  },
  //点击确定或者取消
  open: function (e) {
    this.setData({
      condition: !this.data.condition
    });
  },

  //初始化加载
  onLoad: function (e) {   
    //区划信息
    var that = this;
    tcity.init(that);
    var cityData = that.data.cityData;
    const provinces = [];
    const citys = [];
    const countys = [];
    const provinceId = [];
    const cityId = [];
    const countyId = [];
    const codes = [];
    for (let i = 0; i < cityData.length; i++) {
      provinces.push(cityData[i].divisionName);
      provinceId.push(cityData[i].divisionId);
    }
    //省份完成
    for (let i = 0; i < cityData[0].children.length; i++) {
      citys.push(cityData[0].children[i].divisionName);
      cityId.push(cityData[0].children[i].divisionId)
    }
    //city完成
    for (let i = 0; i < cityData[0].children[0].children.length; i++) {
      countys.push(cityData[0].children[0].children[i].divisionName); 
      countyId.push(cityData[0].children[0].children[i].divisionId); 
    }
    that.setData({
      'provinces': provinces,
      'citys': citys,
      'countys': countys,
      'provinceIds': provinceId,
      'cityIds': cityId,
      'countyIds': countyId,
      'codes':codes,
      'code': cityData[0].children[0].children[0].divisionCode,
      'province': cityData[0].divisionName,
      'city': cityData[0].children[0].divisionName,
      'county': cityData[0].children[0].children[0].divisionName,
      'provinceId': cityData[0].divisionId,
      'cityId': cityData[0].children[0].divisionId,
      'countyId': cityData[0].children[0].children[0].divisionId
    })
    //下级区划加载
    wx.request({
      method: 'GET',
      url: '' + getApp().globalData.wxurl +'/allreq/administrative/divisioncode/' + cityData[0].children[0].children[0].divisionCode + '',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "headMode": getApp().globalData.InitialHeadmode,
      },
      success: function (res) {
        var datas = res.data;
        const streets = [];
        const sioncode = [];
        for (let i = 0; i < datas.length; i++) {
          streets.push(datas[i].divisionName);
          sioncode.push(datas[i].divisionCode);
        }
         that.setData({
          street: streets,
          scode: sioncode,
        })
      },
      fail: function (f) {
        console.log(f)
      },
      
    }); 
    //初始化完成

    //登录信息
      var login_Info = JSON.parse(wx.getStorageSync('login_Information')); //登录基础信息 
      
      that.setData({
        //登录基础信息回写
        userName: login_Info.realName,//用户姓名 
        title_phone: getApp().globalData.phone//用户电话号码
      })
  }, 
  formSubmit:function(e){
    var that = this;
    const data_regex_cordid = that.data.regex_cordid;//身份证校验开关(校验通过为1，未通过为2) 
    const login_Info = JSON.parse(wx.getStorageSync('login_Information')); //登录基础信息
    const headArray = wx.getStorageSync('UserLogin');//头部请求信息
   

    if (data_regex_cordid == 1){
      //从页面获取的信息

      //随机私钥  
      const key = CryptoJS.enc.Utf8.parse(app.globalData.PrivateKey);
      console.log("随机私钥:" + key);

      //加密偏移量
      const options = {
        iv: CryptoJS.enc.Utf8.parse("bskyapp123456789"),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      };

      //CBC加密后的用户姓名
      const encryptedNameData = CryptoJS.AES.encrypt(e.detail.value.name, key, options);
      const encryptedName = encryptedNameData.toString();
      console.log('CBC加密后的用户姓名', encryptedName);
      const form_name = encryptedName;

       //CBC加密后的用户ID
      const encryptedcordID = CryptoJS.AES.encrypt(e.detail.value.cordID, key, options);
      const encryptedId = encryptedcordID.toString();
      console.log('CBC加密后的用户ID：', encryptedId); 
      const form_cordID = encryptedId;


      const form_userId = login_Info.userId ;
      const form_token = login_Info.token;
     
      //区划选择的信息
      const form_cityId = that.data.cityId;
      const form_provinceId = that.data.provinceId;
      const form_properId = that.data.countyId;
      const form_areaId = that.data.areaId;
      const form_areaCode = that.data.areacode;
      const form_index = that.data.index;
      //提交的json
      const indexData = {
        "areaId": form_areaId[form_index],
        "cityId": form_cityId,
        "properId": form_properId,
        "provinceId": form_provinceId,
        "areaCode": form_areaCode[form_index],
        "documentNo": form_cordID,
        "realName": form_name,
        "userId": form_userId
      }
      
      const headmode = {
        'Accept': 'application/json',
        "Content-Type": "application/json;charset=UTF-8",
        "headMode": headArray,
        "token": login_Info.token,
      };
      const url = '/resident/v1/realnameauth';
      var indexJson = JSON.stringify(indexData);
      console.log(indexJson);
      //实名认证数据提交
      HttpRequest.postReq(url, indexJson, headmode, function (res,code) { 
        console.log(res);
        if (code!=200){
          wx.showToast({
            title: res,
            icon: 'none',
            duration: 2000
          })
        }
        var InfoUrl = '/resident/healthcard/info?';
        var headmode = {
          'Accept': 'application/json',
          "Content-Type": "application/json;charset=UTF-8",
          "headMode": headArray,
          "token": login_Info.token,
        }
        var infodata={};
        //判别是否已经拥有健康卡
        HttpRequest.getReq(InfoUrl, infodata,headmode, function (res, code) {
            if (code == 406){
              wx.navigateTo({
                url: '../apply/apply'
              })
            }
            else {
              wx.navigateTo({   
                url: '../Health/Health'
              })
            }
        
        })
      });
    }else{
      wx.showToast({
        title: "身份证校验格式错误",
        icon: 'none',
        duration: 2000
      })
    }
  }
})
